<template>
    <el-upload v-model:file-list="fileList" action="http://goapi.sanjitian.cn/api/files" list-type="picture-card"
        :headers="headers" :show-file-list="false" :on-success="handleAvatarSuccess"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
        <el-icon>
            <Plus />
        </el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>

    <div class="my-img-list">
        <div v-for="item in myImgList" :key="item.id" class="img-container">
            <img :src="item.filePathCos" :alt="item.fileType" />
            <el-icon class="close-btn" @click="removeImage(item)">
                <close />
            </el-icon>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'

interface IFileInfo {
    fileExtension: string
    filePathCos: string
    fileSize: string
    fileType: string
    fileUse: string
    id: number
    mineType: string
    uploadTime: string
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const myImgList = ref<IFileInfo[]>([])
const fileList = ref<UploadUserFile[]>([])

const headers = {
    Authorization: `${localStorage.getItem('token')}`
}

const removeImage = (item: IFileInfo) => {
    myImgList.value = myImgList.value.filter(i => i.id !== item.id)
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    console.log(uploadFile, '#uploadFile')
    console.log(response.data, '#response')
    myImgList.value.push(response.data)
}

</script>
<style lang="scss" scoped>
.my-img-list {
    width: 100%;
    height: 200px;
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;

    .img-container {
        position: relative;
        display: inline-block;
        overflow: hidden;
    }

    img {
        height: 150px;
        width: 150px;
    }

    .close-btn {
        font-size: 20px;
        position: absolute;
        top: 5px;
        right: 5px;
        cursor: pointer;
        color: #f56c6c;
        opacity: 0;
        transition: opacity 0.3s;
    }

    .img-container:hover .close-btn {
        opacity: 1;
    }
}
</style>